package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.employee.Department;
import com.example.chcrm.entity.employee.RoleModels;
import com.example.chcrm.mapper.DepartmentMapper;
import com.example.chcrm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/4/17 1:35
 * @Version 1.0
 */
@Service
public class DepartmentServiceImpl<T> implements DepartmentService<T> {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public ResponseMsg<IPage<Department>> pageList(Department department) {
        // 动态条件构建
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();

        // 部门名称模糊查询
        if (StringUtils.isNotBlank(department.getDepNm())) {
            queryWrapper.like("dep_nm", department.getDepNm());
        }


        // 负责人精确查询
        if (StringUtils.isNotBlank(department.getLeader())) {
            queryWrapper.eq("leader", department.getLeader());
        }

        // 状态筛选
        if (department.getStatus() != null) {
            queryWrapper.eq("status", department.getStatus());
        }

        // 基础条件
        queryWrapper
                .eq("is_deleted", 0)  // 未删除数据
                .orderByDesc("create_time");

        // 检查传入的department.getPage()和getRows()值
        System.out.println("Page: " + department.getPage() + ", Size: " + department.getRows());
        // 执行分页查询
//        IPage<Department> resultPage = departmentMapper.selectPage(page, queryWrapper);
//        Long currentPageRecords = departmentMapper.selectCount(queryWrapper); // 当前页实际返回的记录数[8](@ref)
//        response.success("查询成功");
//        response.setTotal( currentPageRecords.intValue());
//        response.setData(resultPage);
        List<Department> list = departmentMapper.selectList(queryWrapper);
        ResponseMsg<IPage<Department>> iPageResponseMsg = new ResponseMsg<>();
        Page<Department> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(department.getRows());
        page.setCurrent(department.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public ResponseMsg<Object> add(Department dept){
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(dept.getDepNm())){
            msg.fail("请填写部门名称");
            return msg;
        }
        //验证部门名称是否存在
        int num = (departmentMapper.selectCount(new QueryWrapper<Department>()
                .eq("dep_nm",dept.getDepNm())
                .eq("is_deleted",0))).intValue();
        if(num > 0){
            msg.fail("部门已存在");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        String id = RandomHelper.uuid();
        dept.setId(id);
        dept.setStatus(1);
        dept.setIsDeleted(0);
        dept.setCreateTime(new Date());
        departmentMapper.insert(dept);
        //添加操作日志
//        OperateRecord ope = new OperateRecord();
//        ope.setId(RandomHelper.uuid());
//        ope.setOperateType(OperateRecord.OPE_ADD);
//        ope.setOperationId(RandomHelper.uuid());
//        ope.setSourceId(id);
//        ope.setOperationName("admin");
//        operateRecordMapper.insert(ope);

        msg.success("新增成功");
        return msg;
    }

    /**
     * 删除部门
     *
     * @param
     * @param id
     * @return
     **/
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg<Object> delete(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        Department department = departmentMapper.selectById(id);
        if (department == null) {
            msg.fail("删除失败,部门未找到");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        departmentMapper.update(null,new UpdateWrapper<Department>().set("is_deleted",-1).eq("id",department.getId()));
        msg.success("删除成功");
        return msg;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public ResponseMsg<Object> disable(Department dept){
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(dept.getId())){
            msg.fail("未找到选中部门");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<Department>();

        if (dept.getStatus()==1){
            updateWrapper.set("status",1);
            updateWrapper.eq("id",dept.getId());
            departmentMapper.update(null,updateWrapper);
            msg.success("启动成功");
        }else if(dept.getStatus()==0){
            updateWrapper.set("status",0);
            updateWrapper.eq("id",dept.getId());
            departmentMapper.update(null,updateWrapper);
            msg.success("禁用成功");
        }else {
            msg.fail("本次操作失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public ResponseMsg<Object> update(Department dept){
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(dept.getDepNm())){
            msg.fail("请填写部门名称");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        if (StringUtils.isBlank(dept.getId())){
            msg.fail("未找到选中部门");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        int num = (departmentMapper.selectCount(new QueryWrapper<Department>()
                .eq("dep_nm",dept.getDepNm())
                .eq("is_deleted",0))).intValue();
        if(num > 0){
            msg.fail("部门已存在");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<Department>();
        System.out.println(dept);
        if ( StringUtils.isNotBlank(dept.getDepNm())){
            updateWrapper.set("dep_nm",dept.getDepNm());
        }
        if ( StringUtils.isNotBlank(dept.getLeader())){
            updateWrapper.set("leader",dept.getLeader());
        }
        if ( StringUtils.isNotBlank(dept.getLeaderPhone())){
            updateWrapper.set("leader_phone",dept.getLeaderPhone());
        }
        updateWrapper.eq("id",dept.getId());
        departmentMapper.update(null,updateWrapper);
        msg.success("修改成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> selectAllDepartment() {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        QueryWrapper<Department> query = new QueryWrapper<>();
        query.select("id,dep_nm");
        query.eq("is_deleted", 0);
        List<Map<String, Object>> essRole = departmentMapper.selectMaps(query);
        msg.setData(essRole);
        msg.success("查询成功");
        return msg;
    }
}
